import 'dart:async';
import 'dart:convert';

import 'package:amoy_ticket/utils/device_info_plus.dart';
import 'package:amoy_ticket/utils/object_util.dart';
import 'package:amoy_ticket/utils/router/log_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  WebViewPage({Key? key}) : super(key: key);

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> with WidgetsBindingObserver {
  late WebViewController _controller;
  // 上个页面通过路由传过来的参数
  Map _map = {};
  String httpError = '0';
  bool iscache = false;
  String title = '';
  bool hadBg = false;
  late String webviewUrl;

  Duration dutationTime = Duration(milliseconds: 500);
  Timer? timer;

  var deviceInfo;
  @override
  void initState() {
    SystemChrome.setPreferredOrientations([]);
    _map = Get.arguments;
    webviewUrl = _map['url'];
    title = _map['title'] ?? '';
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    //取消强制竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight
    ]);
    deviceInfo = getDeviceInfo();

    super.initState();
  }

  @override
  void dispose() {
    //强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);

    super.dispose();
  }

  //获取h5页面标题
  Future getWebTitle() async {
    String? title = await _controller.getTitle();
    if (ObjectUtil.isNotEmpty(title)) {
      if (mounted)
        setState(() {
          title = title?.replaceAll('"', '');
          this.title = title ?? '';
          debugPrint('#################### $title');
        });
    }
  }

  _appBar(context) {
    return AppBar(
      title: Text(title,
          style: TextStyle(
              color: Color(0xFF333333),
              fontSize: 20,
              fontWeight: FontWeight.bold)),
      leading: new IconButton(
          icon: new Icon(
            Icons.arrow_back,
            color: Color(0XFF727272),
          ),
          onPressed: () {
            if (_map['isRoot'] == 'true') {
              // 返回到首页
            } else {
              _controller.canGoBack().then((value) {
                if (value == true) {
                  _controller.goBack();
                } else {
                  Get.back();
                }
              });
            }
          }),
      centerTitle: true,
      systemOverlayStyle: SystemUiOverlayStyle.dark,
    );
  }

  @override
  Widget build(BuildContext context) {
    LogUtil.get().d(_map['url']);
    //header头信息
    // final headersData = {
    //   // "version": packageInfo?.version?.toString(),
    //   "client-type": 'app',
    //   "platform": Platform.isAndroid ? 'android' : 'ios',
    //   "device": json.encode(deviceInfo),
    // };

    //自定义useragent
    // final userAgent =
    //     "ua-${headersData['platform']}-${headersData['version']}-mobile-app";

    return Scaffold(
      appBar: _appBar(context),
      body: Builder(builder: (BuildContext context) {
        return WebView(
          initialUrl: webviewUrl,
          javascriptChannels: [_toasterJavascriptChannel(context)].toSet(),
          // userAgent: userAgent,
          //JS执行模式
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _controller = webViewController;
          },
          onPageStarted: (String url) {
            print('=======onPageStarted=======');
          },
          onPageFinished: (String url) {
            getWebTitle();
            print('=======onPageFinished=======');
          },
          onWebResourceError: (error) {
            setState(() {
              httpError = error.errorCode.toString();
            });
          },
          gestureNavigationEnabled: true,
        );
      }),
    );
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
      name: 'Toaster',
      onMessageReceived: (JavascriptMessage message) {
        print('sss');
        print(message.message);
        var res = json.decode(message.message);
        switch (res['clientType']) {
          case 'route':
            _controller.getTitle();
            timer?.cancel();
            timer = Timer(dutationTime, () {
              Navigator.pushNamed(context, res['msg'],
                  arguments: res['arguments']);
            });

            break;
          case 'replace':
            // 页面替换
            Navigator.pushReplacementNamed(context, res['msg'],
                arguments: res['arguments']);
            break;
          case 'pop':
            Navigator.of(context).pop();
            break;

          default:
        }
      },
    );
  }
}
